﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
using IntelligentDecisioning.SharePoint.Definition;
using System.Diagnostics;
using IntelligentDecisioning.SharePoint.Logging;
using IntelligentDecisioning.SharePoint.Definition.Fields;

namespace IntelligentDecisioning.SharePoint.Helpers
{
    public class IDSiteColumnHelper: IDSharePointHelper
    {
        #region Constructor

        public IDSiteColumnHelper(SPSite siteCollection, SPWeb targetWeb)
            : base(siteCollection, targetWeb, new NoLog())
        {

        }

        public IDSiteColumnHelper(SPSite siteCollection, SPWeb targetWeb, ILog log)
            : base(siteCollection, targetWeb, log )
        {

        }

        #endregion


        #region Provision Site Columns

        public void ProvisionSiteColumns(List<Field> siteColumns)
        {

            Log.WriteToLog(String.Format("There are {0} site columns to provision", siteColumns.Count.ToString()));

            foreach (Field siteColumn in siteColumns)
            {
                // The sharepoint object model does not provide very good 
                // support for provisioning site colums directly. However, it
                // does allow the injection of <Field> xml. Taking this approach
                // gives us much more fine grained control and importantly allows
                // us to specify the id of the field so that we can reference it
                // elsewhere (e.g. in content types)
                
                // If the field already exists then delete it 
                try
                {
                    SPField field = RootWeb.Fields[new Guid(siteColumn.Id)];
                    field.Delete();
                }
                catch(Exception e)
                {
                    Debug.Write(e.ToString());
                }

                try
                {
                    ProvisionSiteColumn(siteColumn);
                }
                catch (Exception e1) // duplicate name exception?
                {
                    Log.WriteToLog("Unexpected error when provisioning site column", e1);
                    throw;
                }
            }

            RootWeb.Update();
        }

        /// <summary>
        /// Take a single SiteColumn object, get it's provisioning CAML and add the column to the RootWeb.
        /// </summary>
        /// <param name="siteColumn">The SiteColumn ot add to the RootWeb</param>
        public void ProvisionSiteColumn(Field siteColumn)
        {
            Log.WriteToLog(String.Format("Provisioning site column {0}, to group {1}", siteColumn.DisplayName, siteColumn.GroupName)); 
            string xml = siteColumn.GetProvisioningXML();
            RootWeb.Fields.AddFieldAsXml(xml);
            RootWeb.Update();
        }


        public void RemoveSiteColumns(List<Field> siteColumns)
        {

            foreach (Field siteColumn in siteColumns)
            {
                try
                {
                    SPField field = RootWeb.Fields[siteColumn.Id];
                    field.Delete();
                }
                catch(Exception e)
                {
                    Debug.Write(e.ToString());
                }
            }

            RootWeb.Update();
        }

        #endregion

        internal bool SiteColumnExists(String id)
        {
            try
            {
                SPField field = RootWeb.Fields[new Guid(id)];
                return true;
            }
            catch { return false; }
        }
    }
}
